import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/login'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'

// 异步组件 按需加载  （已导入）
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const ProDetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },

    {
      path: '/',
      component: Layout,
      redirect: '/home', /* 重定向 */
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },

    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: MyOrder }
  ]
})

// 全局前置守卫

// 定义一个数组，专门用户存放所有需要权限访问的页面
const authUrl = ['/pay', '/myorder']
// 1. to   往哪里去， 到哪去的路由信息对象
// 2. from 从哪里来， 从哪来的路由信息对象
// 3. next() 是否放行
//    如果next()调用，就是放行
//    next(路径) 拦截到某个路径页面
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  // 数组实例方法includes，判断一个字符串是否包含在另一个字符串中，根据情况返回true或false。  path路径
  if (!authUrl.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }

  // 是权限页面，需要判断token(用户登录标识，登录成功才有)
  const token = store.getters.token /* 用getters全局封装，等同store.state.user.usrInfo.token */
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
